<?php

!defined('IN_VIFRAME') && die('Access Denied.');

class Config extends TLib {
	
	public static
		$Configs = array();
		
	protected static
		$_Loaded = array();

	public static function load($key, $default = array(), $filterAlias = VI_SYSTEM_FILTERALIAS) {
		$paths = Vi::getImportFilesByPath("Config : $key", $filterAlias);
		
		foreach ($paths as $path) {
			if (!self::isLoaded($path)) {
				if (is_file($path)) {
					$file = @include($path);
				} else {
					return false;
				}
				$_Loaded[$path] = true;
				
				if (false === $file) {
					$file = $default;
				}
		
				self::$Configs = $file + self::$Configs;
			}
		}

		return true;
	}
	
	public static function isLoaded($path) {
		return (isset(self::$_Loaded[$path]) && self::$_Loaded[$path]);
	}

	public static function getLoadedFiles() {
		return array_keys(self::$_Loaded);
	}
	
	public static function has($key) {
		$subkeys = explode(':', $key);
		$config  = self::$Configs;
		foreach ($subkeys as $subkey) {
			if (isset($config[$subkey])) {
				$config = $config[$subkey];
			} else {
				return false;
			}
		}
		
		return true;
	}
	
	public static function simpleHas($key) {
		return isset(self::$Configs[$key]);
	}

	public static function get($key) {
		$subkeys = explode(':', $key);
		$config  = self::$Configs;
		foreach ($subkeys as $subkey) {
			if (isset($config[$subkey])) {
				$config = $config[$subkey];
			} else {
				return false;
			}
		}
		
		return $config;
	}
	
	public static function simpleGet($key) {
		return (isset(self::$Configs[$key]) ? self::$Configs[$key] : false);
	}
	
	public static function set($key, $value = VI_CONFIG_RECURSIVESET) {
		if (is_array($key)) {
			if ($value) {
				foreach($key as $cntKey => $cntValue) {
					self::set($cntKey, $cntValue);
				}
			} else {
				self::$Configs = $key + self::$Configs;
			}
		} else {
			$subkeys = explode(':', $key);
			$config  = & self::$Configs;
			foreach ($subkeys as $subkey) {
				if (isset($config[$subkey])) {
					$config = & $config[$subkey];
				} else {
					$config[$subkey] = array();
					$config = & $config[$subkey];
				}
			}
			$config = $value;
		}
		
		return true;
	}
	
	public static function simpleSet($key, $value) {
		self::$Configs[$key] = $value;
		
		return true;
	}
	
	public static function remove($key) {
		$subkeys = explode(':', $key);
		$config  = & self::$Configs;
		foreach ($subkeys as $subkey) {
			if (isset($config[$subkey])) {
				$config = & $config[$subkey];
			} else {
				return true;
			}
		}
		unset($config);
		
		return true;
	}
	
	public static function simpleRemove($key) {
		unset(self::$Configs[$key]);
			
		return true;
	}
	
	public static function getAll() {
		return self::$Configs;
	}
	
	public static function removeAll() {
		self::$Configs = array();
		
		return true;
	}
}
